const error_unknow = -1
const error_unknow_url = -2


import { 
    decodeAddress, 
    signatureVerify
  } from '@polkadot/util-crypto';
import { u8aToHex } from '@polkadot/util';
import { ApiPromise, WsProvider } from '@polkadot/api';

var api = null
var wsProvider = new WsProvider('ws://node:9001'); // 这个是rpc地址，需要根据实际修改
ApiPromise.create({ provider: wsProvider }).then((api_tmp) => {
    api = api_tmp
})
function verify(msg){
    const msg_addr = msg.address
    const msg_timestamp = parseInt(msg.timestamp)
    const msg_sign = msg.sign;
    const publicKey = decodeAddress(msg_addr);
    const hexPublicKey = u8aToHex(publicKey);
    return signatureVerify(JSON.stringify({address:msg_addr, timestamp:msg_timestamp}), msg_sign, hexPublicKey).isValid
}

function handle_post(url, param, cb){
    console.log("handle:", url, "param:", param)
    var rtn = {result: -1, msg:"error_unknow"}
    switch(url){
        default: {
            rtn.result = -2;
            rtn.msg = "url{" + url + "} unknow";
            cb(rtn)
            break;
        }
    }
    
}
async function handle_get(url, cb){
    console.log("url is ", url)
    if (url.indexOf("/latest_nft") == 0){
        let rtn = []
        var param_list = url.split("/")
        param_list.splice(0,2)
        let symbol = await api.query.nft.symbol(param_list[0])
        let nft_count = await api.query.nft.lastNftIndex(param_list[0])
        nft_count = nft_count.toHuman()
        symbol = symbol.toHuman();
        for(var i = parseInt(nft_count); i > 0; i--){
            if (rtn.length == 5){
                break;
            }
            let uri = await api.query.nft.nftUri(param_list[0], i)
            uri = uri.toHuman()
            rtn.push({
                symbol: symbol,
                id: i,
                uri: JSON.parse(uri)
            })
        }
        cb(rtn) 
    }else{
        cb({
            status: -1,
            message: "no function found"
        })
    }
    
}


export {handle_post, handle_get};